require('dotenv').config();
const express = require('express');
const path = require('path');
const cors = require('cors');
const fileUpload = require('express-fileupload');
const fs = require('fs');
const { initDatabase } = require('./db');

// 初始化必要目录
const initDirectories = () => {
  const directories = [
    process.env.TEMP_DIR,
    process.env.RESULTS_DIR,
    path.dirname(process.env.DATABASE_PATH)
  ];
  
  directories.forEach(dir => {
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }
  });
};

// 初始化应用
const app = express();
const PORT = process.env.PORT || 3000;

// 初始化数据库和目录
initDirectories();
initDatabase();

// 中间件配置
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload({
  limits: { fileSize: 50 * 1024 * 1024 }, // 50MB上限
  tempFileDir: process.env.TEMP_DIR,
  useTempFiles: true
}));

// 静态文件服务
app.use(express.static(path.join(__dirname, '../public')));

// 路由配置
app.use('/api/provinces', require('./routes/provinceRoutes'));
app.use('/api/excel', require('./routes/excelRoutes'));

// 页面路由
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, '../public/index.html'));
});

app.get('/manage', (req, res) => {
  res.sendFile(path.join(__dirname, '../public/manage.html'));
});

app.get('/excel', (req, res) => {
  res.sendFile(path.join(__dirname, '../public/excel.html'));
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error('服务器错误:', err.stack);
  res.status(500).json({
    success: false,
    error: process.env.NODE_ENV === 'development' ? err.message : '服务器内部错误'
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`✅ 服务已启动：http://localhost:${PORT}`);
  console.log(`📌 1. 运费计算：/ | 2. 报价维护：/manage | 3. Excel测算：/excel`);
});

module.exports = app;
